const LRU = require('lru-cache')

let commonOptions = {
    max: 100,
    maxAge: 600 * 1000,//单位是毫秒
}
let acOptions = {
    max: 10,
    maxAge: 60 * 1000,//单位是毫秒
}

let htmlLRU = {
    'standard':new LRU(commonOptions),
    'detail' : new LRU(commonOptions),
    'ac': new LRU(acOptions)
}

module.exports = {
    //修正缓存的key
    getCacheKey(urlPath) {
        var urlPathReg = /\.jpg|\.png|\.gif|\.ico|\.js|\.css$/i
        var urlPathElseReg = /\.[a-zA-z0-9]+$/i
    
        //静态资源文件，不缓存
        if(urlPathReg.test(urlPath)) return ''
        
        if (urlPath.endsWith('.html') || urlPath.endsWith('.htm')) {
          
        } else if(urlPath.endsWith('/')) {
    
        } else if(urlPath.endsWith('.xml')) {
            
        } else if (urlPathElseReg.test(urlPath)) {//非法不识别的文件，不缓存
          urlPath = ''
        } else {
          urlPath = urlPath + '/'
        }
        return urlPath
    },
    //获取缓存类别，目前有ac、detail、standard
    //ac由于在中间件缓存，需要通过setAcItem、getAcItem操作
    getCacheType(path) {
        let cacheKeyType =  'standard'
        var reg = /\/\w+\/\w+_detail\//
        if (reg.test(path)) {
            cacheKeyType = 'detail'
        }

        return cacheKeyType
    },
    setItem(path, html) {
        if (!path || !html) return

        let cacheKeyType = this.getCacheType(path)
        
        htmlLRU[cacheKeyType].set(path,html)
    },
    getItem(path){
        if (!path) return ''
        let cacheKeyType = this.getCacheType(path)
        
        return htmlLRU[cacheKeyType].get(path)
    },
    //主要支持AC业务场景的页面
    setAcItem(path, html) {
        if (!path || !html) return

        let cacheKeyType = 'ac'
        
        htmlLRU[cacheKeyType].set(path,html)
    },
    //主要支持AC业务场景的页面
    getAcItem(path){
        if (!path) return ''

        let cacheKeyType = 'ac'
        
        return htmlLRU[cacheKeyType].get(path)
    }
}
